#!/usr/bin/env python
# coding=utf-8


import os
import sys
import re
import optparse
import winsound
import glob

from os.path import join as pjoin

models = ('je609', 'nx005', 'nx007', 'jg500')
nickName = {'je609': '09DOP',
		'nx005': '09OverseaSL',
		'nx007': '09OverseaH',
		'jg500': '09CH'}
targets = ('Rebuild', 'Build')
configs = ('Release', 'Debug')
platforms = ('Windows Mobile 5.0 Pocket PC SDK (ARMV4I)', 
			'09Light Platform (ARMV4I)',
			'WS_NX005 (ARMV4I)')

modelPlatform =  {'je609': platforms[1],
		'nx005': platforms[2],
		'nx007': platforms[1],
		'jg500': platforms[1]}

buildlog = open('build.log', 'w')

def create_build_sequence(model):
	'get the projects to be built in order.\n'
	modelFolder = model + 'Apl'
	# folder for AplCommonBase
	acbFolder = pjoin(modelFolder, 'AplCommonBase')
	# folder for AplCommon model
	acmFolder = pjoin(modelFolder, 'AplCommon' + nickName[model])
	# folder for VoiceBase
	vbFolder = pjoin(modelFolder, 'VoiceBase')
	# folder for Voice model
	vmFolder = pjoin(modelFolder, 'Voice' + nickName[model])
	return (
			# AIPI_Voice
			#pjoin(acbFolder, 'AIPI_Voice', 'AIPI_Voice.vcproj'),
			# VoiceLibBase
			pjoin(acbFolder, 'VoiceLibBase', 'VoiceLibBase.vcproj'),
			# VoiceLib
			pjoin(acmFolder, 'VoiceLib', 'VoiceLib.vcproj'),
			# VoicePlayBase
			pjoin(vbFolder, 'VoicePlayBase', 'VoicePlayBase.vcproj'),
			# VoicePlay
			pjoin(vmFolder , 'VoicePlay', 'VoicePlay.vcproj'),
			# VoiceMainBase
			pjoin(vbFolder, 'VoiceMainBase', 'VoiceMainBase.vcproj'),
			# VoiceMain
			pjoin(vmFolder , 'VoiceMain', 'VoiceMain.vcproj')
			)


def remove(model):
	'Remove model folder.\n'
	cmd = 'rmdir ' + '/S /Q ' + model + 'Apl '
	print >> buildlog, "call cmd: " , cmd
	return os.system(cmd)


def download(model):
	'Call $(model)GetFiles.bat\n'
	cmd = model + 'GetFiles.bat '
	print >> buildlog, "call cmd: " , cmd
	return os.system(cmd)


def update(model):
	'Enter the model folder and call batch\DEV_AutoUpdata.bat.\n'
	try:
		os.chdir(model+'Apl')
	except Exception:
		print "Cannot find foler " + model + 'Apl' + '\n'
		return None
	cmd = 'batch\\DEV_AutoUpdate.bat '
	print >> buildlog, "call cmd: " , cmd
	p = os.system(cmd)
	os.chdir('..')
	return p


def build_project(projf, target, config, platform):
	"""Build the project,
	target : Rebuild, Build
	config : Release, Debug
	platform: Windows Mobile 5.0 Pocket PC SDK (ARMV4I), 09Light Platform (ARMV4I), WS_NX005 (ARMV4I)
	"""
	#cmd = 'msbuild '									\
	#		+ projf + ' '								\
	#		+ '/t:"' + target + '" '					\
	#		+ '/p:Configuration="' + config + '" '		\
	#		+ '/p:Platform="' + platform + '" '		
	cmd = 'vcbuild '									\
			+ '/rebuild '								\
			+ projf + ' '								\
			+ '"' + config + '|' + platform + '"'		 
	#print "call cmd: " , cmd
	return os.popen(cmd, 'r')


def filter_error(fp, logfn):
	nerror = 0
	nwarn = 0
	ret = True
	lines = fp.readlines()
	for  line in lines:
		r = re.search(r'\s+(\d+)\s+warning', line)
		if r:
			nwarn = int(r.groups()[0])
			print nwarn, ' warnings'
			print >> buildlog, nwarn, ' warnings'
		r = re.search(r'\s+(\d+)\s+error', line)
		if r:
			ret = False
			nerror = int(r.groups()[0])
			print nerror, ' errors'
			print >> buildlog, nerror, ' errors'
			if nerror>0:
				winsound.Beep(3000,400)
		line = fp.readline()
	if not os.path.isdir('log'):
		os.mkdir('log')
	logfn = logfn.replace('\\', '_')
	logfn = logfn.replace('|', '_')
	logfn = str(nerror) + '_ERROR_' + str(nwarn) + '_WARNING__' +logfn + '.log'
	logfn = 'log\\' + logfn.replace('\\', '_')
	logfp = open(logfn, 'w')
	logfp.writelines(lines)
	logfp.close()
	return ret

def download_update_model(model):
	print "downloading " + model
	print >> buildlog, "downloading " + model
	download(model)
	#wait_file(download(model))
	print "updating " + model
	print >> buildlog, "updating " + model
	update(model)
	#wait_file(update(model))


def remove_model(model):
	print "removing " + model
	print >> buildlog, "removing " + model
	remove(model)

def download_model(model):
	print "downloading " + model
	print >> buildlog, "downloading " + model
	download(model)


def update_model(model):
	print "updating " + model
	print >> buildlog, "updating " + model
	update(model)
	update(model)

def build_model(model):
	del_pubinc(model)
	print "building " + model
	print >> buildlog, "building " + model
	for cfg in (('Rebuild', 'Debug', platforms[0]), 
			('Rebuild', 'Debug', modelPlatform[model]),
			('Rebuild', 'Release', modelPlatform[model])):
		for projf in create_build_sequence(model):
			info =  "building " + cfg[0] + '|' + cfg[1] + '|' + cfg[2] + ' ' + projf
			print info
			print >> buildlog, info
			fp = build_project(projf, cfg[0], cfg[1], cfg[2])
			logfn = model + ' ' + cfg[1] + '_' + cfg[2] + projf
			filter_error(fp, logfn)

def del_pubinc(model):
	print "delete public header " + model
	model_folder = model+'Apl'
	pubinc_patterns = (r'%s\Global\publicinc\VL*.h'%(model_folder,),
		r'%s\Global\*\publicinc\VL*.h'%(model_folder,),
		r'%s\Global\*\*\publicinc\VL*.h'%(model_folder,),
		r'%s\Global\*\*\*\publicinc\VL*.h'%(model_folder,),
		r'%s\Global\publicinc\VP*.h'%(model_folder,),
		r'%s\Global\*\publicinc\VP*.h'%(model_folder,),
		r'%s\Global\*\*\publicinc\VP*.h'%(model_folder,),
		r'%s\Global\*\*\*\publicinc\VP*.h'%(model_folder,),
		r'%s\Global\publicinc\VoicePlay*.h'%(model_folder,),
		r'%s\Global\*\publicinc\VoicePlay*.h'%(model_folder,),
		r'%s\Global\*\*\publicinc\VoicePlay*.h'%(model_folder,),
		r'%s\Global\*\*\*\publicinc\VoicePlay*.h'%(model_folder,)
		)
	for p in pubinc_patterns:
		for f in glob.glob(p):
			print >> buildlog, "delete public header : ", f
			os.remove(f)


def parse_args():
	parser = optparse.OptionParser()
	parser.add_option('-m', '--model', action='append', type='string', dest='model', help='add a model(je609, nx005, nx007, jg500, all) to process')
	parser.add_option('-r', '--remove', action='store_true', dest='remove', default=False, help='remove model folder')
	parser.add_option('-d', '--download', action='store_true', dest='download', default=False, help='download model src')
	parser.add_option('-u', '--update', action='store_true', dest='update', default=False, help='call batch\\DEV_AutoUpdate')
	parser.add_option('-b', '--build', action='store_true', dest='build', default=False, help='remove model folder')
	(option,arg) = parser.parse_args()
	if not option.model:
		sys.exit(0)
	if 'all' in option.model:
		option.model = models
	for m in option.model:
		if not m in models:
			print 'model error: ', m
			sys.exit(1)
	return option

def proc_option(option):
	for model in option.model:
		if option.remove:
			remove_model(model)
		if option.download:
			download_model(model)
		if option.update:
			update_model(model)
		if option.build:
			build_model(model)


def main():
	opt = parse_args()
	proc_option(opt)


if __name__ == '__main__':
	main()


